// pages/Category/Category.js
import {
  querySecondaryCategories,
  queryTopCategories,
  queryTertiaryCategories,
  queryComprehensiveCategoryList,
  queryProductListConditionalByCategoryId
} from "../../service/category"
import {
  queryHomePageProductList
} from "../../service/home-page"

import {
  queryBrandWithLetterInfo
} from "../../service/brand"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 商品分类 or 品牌索引
    activeTabIndex: '0',
    // 一级分类列表
    topCategoryList: [],
    // 二级分类激活项
    activeSecondaryCategoryIndex: 0,
    // 二级分类滚动距离
    secondaryScrollLeft: 0,
    // 三级分类激活项
    activeTertiaryCategoryIndex: 0,
    // 三级分类滚动距离
    tertiaryScrollLeft: 0,
    // 综合列表
    comprehensiveCategoryList: [],
    // 侧边栏激活索引
    asideActiveIndex: 0,
    // 展示方式 0-横排，1-竖排
    displayMethod: 0,
    // 商品列表
    productList: [],
    // 当前页
    page: 1,
    // 页面大小
    pageSize: 10,
    // 二级分类宽度
    secondaryWidth: null,
    // 三级分类宽度
    tertiaryWidth: null,
    // 排序状态0-根据销量，1-根据价格
    orderByStatus: 0,
    // 价格排序0-升序1-降序 
    priceOrder: -1,
    // 当前页
    page: 1,
    // 页面大小
    pageSize: 10,
    // 商品列表
    productList: [],
    // 品牌列表
    brandList: [],
    // 品牌索引
    brandIndexBarIndex: [],
    // 商品列表滑动距离
    scrollTop: 0
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    // 请求一级分类
    const topCategoryRes = await queryTopCategories()
    this.setData({
      topCategoryList: topCategoryRes.data
    })
    console.log("一级分类列表", topCategoryRes.data);
    // 请求综合列表
    const comprehensiveRes = await queryComprehensiveCategoryList(this.data.topCategoryList[0].id)
    console.log("综合列表", comprehensiveRes.data);
    this.setData({
      comprehensiveCategoryList: comprehensiveRes.data
    })
    this.loadData()
    // 请求品牌数据
    const brandList = await queryBrandWithLetterInfo()
    console.log('品牌数据', brandList.data);
    const brandIndexList = brandList.data.map(item => item.letter)
    console.log("品牌索引数据", brandIndexList);
    this.setData({
      brandList: brandList.data,
      brandIndexBarIndex: brandIndexList
    })
  },
  /**
   * 点击前往搜索页面
   */
  onTapNavigateToSearchPage() {
    wx.navigateTo({
      url: '/pages/Search/Search',
    })
  },
  /**
   * 点击前往品牌相关商品页面
   */
  onTapNavigateToBrandRelationProduct(event) {
    console.log(event);
    const brandId = event.currentTarget.dataset.brandId
    const brandName = event.currentTarget.dataset.brandName
    wx.navigateTo({
      url: `/pages/ProductList/ProductList?searchType=${2}&keyword=${brandId}&title=${brandName}`,
    })
  },

  /**
   * 点击前往分类相关的页面
   */
  onTapNavigateToCategoryRelationProduct(event) {
    const categoryId = event.currentTarget.dataset.categoryId
    const categoryName = event.currentTarget.dataset.categoryName
    wx.navigateTo({
      url: `/pages/ProductList/ProductList?searchType=${1}&keyword=${categoryId}&title=${categoryName}`,
    })
  },
  /**
   * 加载数据
   */
  async loadData() {
    const categoryId = this
      .data
      .comprehensiveCategoryList[this.data.activeSecondaryCategoryIndex]
      .subCategoryList[this.data.activeTertiaryCategoryIndex]
      .id
    const status = this.data.orderByStatus
    const productListRes = await queryProductListConditionalByCategoryId(categoryId, status, this.data.priceOrder, this.data.page, this.data.pageSize)
    this.setData({
      productList: productListRes.data.records
    })
    console.log(`成功加载第${this.data.page}页分类数据`, categoryId, this.data.productList);
  },
  /**
   * 商品列表滑动到底部
   */
  async onScrollToLower() {
    console.log("加载新一页数据");
    this.data.page = this.data.page + 1
    const categoryId = this
      .data
      .comprehensiveCategoryList[this.data.activeSecondaryCategoryIndex]
      .subCategoryList[this.data.activeTertiaryCategoryIndex]
      .id
    const status = this.data.orderByStatus
    const productListRes = await queryProductListConditionalByCategoryId(categoryId, status, this.data.priceOrder, this.data.page, this.data.pageSize)
    this.setData({
      productList: [...this.data.productList, ...productListRes.data.records]
    })
    console.log(`成功加载第${this.data.page}页分类数据`, categoryId, this.data.productList);
  },
  /**
   *  点击前往商品详情页
   */
  onTapCheckProductDetail(event) {
    const productId = event.currentTarget.dataset.productId
    console.log(productId);
    wx.navigateTo({
      url: `/pages/Product/Product?productId=${productId}`,
    })
  },
  /**
   *  点击排序按钮
   */
  async onTapOrderbyButton(event) {
    const status = Number(event.currentTarget.dataset.status)
    const oldStatus = Number(this.data.orderByStatus)
    if (status === 0 && oldStatus === 0) {
      return
    } else if (status === 1 && oldStatus === 1) {
      this.setData({
        priceOrder: this.data.priceOrder === 0 ? 1 : 0
      })
    } else if (status === 0 && oldStatus === 1) {
      this.setData({
        orderByStatus: 0,
        priceOrder: -1
      })
    } else if (status === 1 && oldStatus === 0) {
      this.setData(({
        orderByStatus: 1,
        priceOrder: 0
      }))
    }
    this.data.page = 1
    await this.loadData()
    this.setData({
      scrollTop: 0
    })
  },
  /**
   * 点击二级菜单项
   */
  async onTapSecondaryCategoryItem(event) {
    if (!this.data.secondaryWidth) {
      const scrollRect = await this.getElementRect("#secondary-category-list")
      this.data.secondaryWidth = scrollRect.width
    }
    const index = event.currentTarget.dataset.index
    const offsetLeft = event.currentTarget.offsetLeft
    const rect = await this.getElementRect(`#secondary-${index}`)
    const scrollLeft = offsetLeft + rect.width / 2 - this.data.secondaryWidth / 2
    this.setData({
      activeSecondaryCategoryIndex: index,
      secondaryScrollLeft: scrollLeft,
      tertiaryScrollLeft: 0,
      activeTertiaryCategoryIndex: 0,
      orderByStatus: 0,
      priceOrder: -1,
      page: 1
    })
    this.data.page = 1
    await this.loadData()
    this.setData({
      scrollTop: 0
    })
  },
  /**
   * 点击三级菜单项
   */
  async onTapTeriaryCategoryItem(event) {
    if (!this.data.tertiaryWidth) {
      const scrollRect = await this.getElementRect("#tertiary-category-list")
      this.data.tertiaryWidth = scrollRect.width
    }
    const index = event.currentTarget.dataset.index
    const offsetLeft = event.currentTarget.offsetLeft
    const rect = await this.getElementRect(`#tertiary-${index}`)
    const scrollLeft = offsetLeft + rect.width / 2 - this.data.tertiaryWidth / 2
    this.setData({
      tertiaryScrollLeft: scrollLeft,
      activeTertiaryCategoryIndex: index
    })
    this.data.page = 1
    await this.loadData()
    this.setData({
      scrollTop: 0
    })
  },

  // 封装成 Promise 函数（可复用）
  getElementRect(selector) {
    return new Promise((resolve) => {
      const query = wx.createSelectorQuery().in(this);
      query
        .select(selector)
        .boundingClientRect((res) => {
          resolve(res); // 成功时返回节点信息
        })
        .exec();
    });
  },

  /**
   * 点击切换展示方式
   */
  onTapChangeDisplayMethod() {
    this.setData({
      displayMethod: this.data.displayMethod === 0 ? 1 : 0
    })
  },
  /**
   * 点击侧边栏
   */
  async onTapAsideItem(event) {
    const index = event.currentTarget.dataset.index
    const categoryId = event.currentTarget.dataset.categoryId

    // 请求综合列表
    const comprehensiveRes = await queryComprehensiveCategoryList(categoryId)
    this.setData({
      asideActiveIndex: index,
      secondaryScrollLeft: 0,
      tertiaryScrollLeft: 0,
      activeSecondaryCategoryIndex: 0,
      activeTertiaryCategoryIndex: 0,
      orderByStatus: 0,
      priceOrder: -1,
      comprehensiveCategoryList: comprehensiveRes.data
    })
    console.log("综合列表", comprehensiveRes.data);
    this.data.page = 1
    await this.loadData()
    this.setData({
      scrollTop: 0
    })
  },
  // 更改商品索引或者品牌索引
  onTapChangeTabIndex(event) {
    this.setData({
      activeTabIndex: event.currentTarget.dataset.index
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})